function CreateDatePicker(){
  $.datepicker.setDefaults(
    $.extend($.datepicker.regional[''])
  );
  $('#fromDatepicker').datepicker();
  $('#toDatepicker').datepicker();
}

function downloadArticle (){
	  if (m_rawRecordId >= 0) {
		  var rawRecordId = m_resultSet[m_rawRecordId].data.id;
		  
		  var newForm = jQuery('<form>', {
			    'id': 'download-form',
		        'action': PM_URI + '/pm/download',
		        'target': '_top'
		    }).append(jQuery('<input>', {
		        'name': 'troveIds',
		        'value': rawRecordId,
		        'type': 'hidden'
		    }));

			newForm.append(jQuery('<input>', {
				'name': 'downloadType',
		        'value': GetDownloadTypeString("pdfSingleDownloadRadioButton","txtSingleDownloadRadioButton"),
		        'type': 'hidden'
			}));
		  
		  newForm.appendTo($('body'));
		  newForm.submit();
	  }
}

function downloadCheckedArticles (){
	var fromDate = $('#fromDatepicker').val();
	var toDate = $('#toDatepicker').val();
	
	var articlesToDownload = "";
	if(fromDate.length === 0 && toDate.length === 0){
		articlesToDownload = GetCheckedItemsIDString();
	}
	else{
		articlesToDownload = GetDateRangeIDStringOrEmptyStringOrAlert(fromDate, toDate);
	}
	
	if(articlesToDownload.length > 0){
		var newForm = jQuery('<form>', {
		    'id': 'download-form',
	        'action': PM_URI + '/pm/download',
	        'target': '_top'
	    }).append(jQuery('<input>', {
	        'name': 'troveIds',
	        'value': articlesToDownload,
	        'type': 'hidden'
	    }));
		
		newForm.append(jQuery('<input>', {
			'name': 'downloadType',
	        'value': GetDownloadTypeString("pdfMultiDownloadRadioButton","txtMultiDownloadRadioButton"),
	        'type': 'hidden'
		}));
		newForm.appendTo($('body'));
	    newForm.submit();
	}
}

function GetCheckedItemsIDString(){
	articlesToDownload = "";
	
	for(var i=0; i < m_resultSet.length; i++){
		var cb = document.getElementById("RVLCB-"+i);

		if(cb != null && ResultRemoved(i) === false){
			if(cb.checked){
				if(i == m_resultSet.length-1){
					articlesToDownload += m_resultSet[i].data.id;
				}
				else{
					articlesToDownload += m_resultSet[i].data.id + ",";
				}
			}
		}
	}
	
	return articlesToDownload;
}

function GetDateRangeIDStringOrEmptyStringOrAlert(fromDate, toDate){
	var fromDateArr = fromDate.split("/");
	var toDateArr = toDate.split("/");
	
	if(fromDateArr.length === 3 && toDateArr.length === 3){
		var fromDay = parseInt(fromDateArr[1]);
		var fromMonth = parseInt(fromDateArr[0]);
		var fromYear = parseInt(fromDateArr[2]);
		
		var toDay = parseInt(toDateArr[1]);
		var toMonth = parseInt(toDateArr[0]);
		var toYear = parseInt(toDateArr[2]);
		
		if(AreDatesFormattedCorrectly(fromDay, fromMonth, fromYear, toDay, toMonth, toYear) === true){
			return GetArticlesInDateRangeString(fromDay, fromMonth, fromYear, toDay, toMonth, toYear);
		}
		else{
			alert("Dates are not formatted correctly");
			return "";
		}
	}
	else{
		alert("Please format dates as MM/DD/YYYY (00/00/YYYY for " +
				"a specific year, MM/00/YYYY for a specific month in a year). Leave date pickers blank for" +
				" only selected articles");
		
		return "";
	}
}

function AreDatesFormattedCorrectly(fromDay, fromMonth, fromYear, toDay, toMonth, toYear){
	if(fromYear <= toYear){
		if(fromYear === toYear && fromMonth <= toMonth){
			if(fromMonth === toMonth && fromDay <= toDay){
				if(fromDay > toDay){
					return false;
				}
				else{
					return true;
				}
			}
			else if(fromMonth > toMonth){
				return false;
			}
			else{
				return true;
			}
		}
		else{
			return true;
		}
	}
	else{
		return false;
	}
}

function GetArticlesInDateRangeString(fromDay, fromMonth, fromYear, toDay, toMonth, toYear){
	articlesToDownload = "";
	
	for(var i=0; i < m_resultSet.length; i++){
		if(ResultRemoved(i) === false){
			var recDateArr = m_resultSet[i].data.date.split("-");
			
			if(recDateArr.length === 3)
			{
				recDay = parseInt(recDateArr[2]);
				recMonth = parseInt(recDateArr[1]);
				recYear = parseInt(recDateArr[0]);
				
				if(AreDatesFormattedCorrectly(fromDay, fromMonth, fromYear, recDay, recMonth, recYear) === true
						&& AreDatesFormattedCorrectly(recDay, recMonth, recYear, toDay, toMonth, toYear) === true){
					if(i == m_resultSet.length-1){
						articlesToDownload += m_resultSet[i].data.id;
					}
					else{
						articlesToDownload += m_resultSet[i].data.id + ",";
					}
				}
			}
		}
	}
	
	return articlesToDownload;
}

function GetDownloadTypeString(pdfRadioButtonId, txtRadioButtonId){	
	var pdfRadioButton = document.getElementById(pdfRadioButtonId);
	var txtRadioButton = document.getElementById(txtRadioButtonId);
	
	downloadType = "";
	
	if(pdfRadioButton.checked){
		downloadType = "pdf";
	}
	else if(txtRadioButton.checked){
		downloadType = "txt";
	}
	
	return downloadType;
}

function SelectAllItemsInRawView() {
	var selectAllCB = document.getElementById("selectAllCheckbox");
	for(var i = 0; i < m_resultSet.length; i++){
		var cb = document.getElementById("RVLCB-"+i);
		if(cb != null){
			cb.checked = selectAllCB.checked;
		}	
	}
}

function removeDDMOptions(DDMId)
{
	var DDM = document.getElementById(DDMId);
	
	if(DDM != null){
	    var i;
	    for(i=DDM.options.length-1;i>=0;i--)
	    {
	    	DDM.remove(i);
	    }
	}
}

function GetLocationsForDDM(DDMId){	
	CreateDDMOption("All","All",DDMId);
	
	var uri = PM_URI + '/pub/getlocations';
    $.getJSON(uri, function (data, status, jqXHR) {
      if (status == "success") {
    	data.locations.sort();
		for(var locId in data.locations){
			CreateDDMOption(data.locations[locId],data.locations[locId],DDMId);
		}
      }
    })
	.done(function() { console.log( "second success" ); })
	.fail(function() { console.log( "error" ); })
	.always(function() { console.log( "complete" ); });
}

function CreateDDMOption(text,value,DDMId){
	var DDM = document.getElementById(DDMId);
	if(DDM != null){
		var optNew = document.createElement("option");
		DDM.options.add(optNew);
		optNew.text = text;
		optNew.value = value;
	}
}

function AddIsHiddenToResult(id, publisherInfo){
	var e = document.getElementById("selectPublisherLocationDDM");
	var publisherLocation = e.options[e.selectedIndex].value;
	
	if(publisherLocation !== "All")
	{
		if(publisherInfo.location !== publisherLocation){
			m_resultSet[id].isHidden = true;
		} 
		else{ 
			m_resultSet[id].isHidden = false; 
		}
	}
	else{
		m_resultSet[id].isHidden = false; 
	}
}

function ResultRemoved(id){ 
	return m_resultSet[id].isHidden; 
}

function GetTotalRecordsFoundAndSetTotalRecords(){
	var recordsFound = 0;
	var totalRecs = m_totalRecs;
	for(var i = 0; i < m_resultSet.length; i++){
		if(ResultRemoved(i) === false){
			recordsFound++;
			totalRecs--;
		}
	}
	
    $('td#n11').html(totalRecs);
	return recordsFound;
}

function RefillAndSetSelectedValueForCurrentDDM(){
	removeDDMOptions("selectPublisherLocationDDMCurrent");
	
	GetLocationsForDDM("selectPublisherLocationDDMCurrent");
	
	var e = document.getElementById("selectPublisherLocationDDM");
	if(e != null){
		var publisherLocation = e.options[e.selectedIndex].value;
		
		if(publisherLocation.length != 0){
			$('select#selectPublisherLocationDDMCurrent').val(publisherLocation);
	    }
		else{
			$('select#selectPublisherLocationDDMCurrent').val('All');
		}
	}
}

function FilterCurrentResultsByPublisherLocation(){
	var e = document.getElementById("selectPublisherLocationDDMCurrent");
	var publisherLocation = e.options[e.selectedIndex].value;
	
	$('select#selectPublisherLocationDDM').val(publisherLocation);
	if (m_resultSet !== null) {
	   for (var i = 0; i < m_resultSet.length; i++) {
	     if (m_resultSet[i].marker !== null) {
	       m_resultSet[i].marker.setPosition(null);
	       m_resultSet[i].marker = null;
	     }
	   }
	}
	_updateMapDisplay(0);
	_updateCurrQueryPane();
}

function SetUpOnEnterForNewQuery(){
	$("#newQueryPaneMainDiv").keydown(function (event) {
        if (event.keyCode == 13) {
          $("#nq-pb12").click();
        }
      });
}

function SetupQueryPage(){
	removeDDMOptions("selectPublisherLocationDDM");
	GetLocationsForDDM("selectPublisherLocationDDM");
	ChangeToSimple();
}

function ChangeToAdvanced(){
	document.getElementById('orRow').style.display = "";
	document.getElementById('excludeRow').style.display = "";
	document.getElementById('publisherRow').style.display = "";
}

function ChangeToSimple(){
	document.getElementById('orRow').style.display = "none";
	document.getElementById('excludeRow').style.display = "none";
	document.getElementById('publisherRow').style.display = "none";
	
    $('input#excludeTermsInput').val('');
    $('input#orTermsInput').val('');
    $('select#selectPublisherLocationDDM').val('All');
}